package com.agent.membership.service;

import com.agent.common.constant.CommonConstants;
import com.agent.membership.entity.MembershipSubscription;
import com.agent.membership.mapper.MembershipSubscriptionMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.List;

/**
 * 自动续费服务
 * @author Jeff_Wan
 * @description 处理会员订阅的自动续费逻辑
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AutoRenewalService {
    private final MembershipSubscriptionMapper subscriptionMapper;
    private final MembershipService membershipService;

    /**
     * 每日检查自动续费任务(UTC时间)
     */
    @Scheduled(cron = "0 0 2 * * ?", zone = "UTC")
    public void checkAutoRenewals() {
        log.info("开始自动续费检查(UTC时间: {})", LocalDate.now(ZoneOffset.UTC));

        // 获取UTC时间明天过期的订阅
        LocalDate tomorrowUTC = LocalDate.now(ZoneOffset.UTC).plusDays(1);
        List<MembershipSubscription> subscriptions =
                subscriptionMapper.findExpiringSubscriptions(tomorrowUTC);

        for (MembershipSubscription subscription : subscriptions) {
            try {
                log.info("处理自动续费: userId={}", subscription.getUserId());
                membershipService.processAutoRenewal(subscription);
            } catch (Exception e) {
                log.error("自动续费失败: userId={}", subscription.getUserId(), e);
            }
        }
        log.info("自动续费检查完成. 处理{}个订阅", subscriptions.size());
    }

    /**
     * 处理过期订阅(UTC时间)
     */
    @Scheduled(cron = "0 0 3 * * ?", zone = "UTC")
    public void handleExpiredSubscriptions() {
        LocalDate yesterdayUTC = LocalDate.now(ZoneOffset.UTC).minusDays(1);
        List<MembershipSubscription> expiredSubs =
                subscriptionMapper.findExpiredSubscriptions(yesterdayUTC);

        for (MembershipSubscription sub : expiredSubs) {
            try {
                // 降级为免费用户
                sub.setPlanType(CommonConstants.MEMBER_FREE);
                sub.setSubscriptionType(CommonConstants.SUBSCRIPTION_MONTHLY);
                sub.setStatus("EXPIRED");
                subscriptionMapper.updateById(sub);

                // 更新用户服务
                membershipService.updateUserMembership(
                        sub.getUserId(),
                        CommonConstants.MEMBER_FREE,
                        CommonConstants.SUBSCRIPTION_MONTHLY
                );

                log.info("降级用户为免费会员: userId={}", sub.getUserId());
            } catch (Exception e) {
                log.error("降级处理失败: userId={}", sub.getUserId(), e);
            }
        }
        log.info("过期订阅处理完成. 处理{}个订阅", expiredSubs.size());
    }
}